<template>
  <div class="content">
    <!-- 客户添加修改弹窗 -->
    <div class="scroll-view-box" v-loading="submitBtn">
      <div class="user-title-box">基本信息</div>
      <el-form label-width="120px" :inline="true" :model="formCustomer" :rules="dLogUserRules" ref="dLogUserRules"
        label-position="top">
        <el-form-item label="客户头像">
          <div class="avater-box">
            <el-upload action="#" list-type="picture-card" :show-file-list="false" :on-change="change_file"
              accept=".png,.jpeg,.jpg,.webp" :auto-upload="false">
              <img v-if="formCustomer.imgUrl" :src="formCustomer.imgUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="formCustomer.name" placeholder="输入客户名称" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input maxlength="11" type="number" oninput="if(value.length > 11) value=value.slice(0, 11)"
            v-model="formCustomer.phone" placeholder="输入手机号" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="customer_type">
          <el-select filterable v-model="formCustomer.customer_type" placeholder="选择客户类型" clearable class="input-width">
            <el-option v-for="item in customerTypeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户性别" prop="customer_sex">
          <div class="input-width">
            <el-radio-group v-model="formCustomer.customer_sex">
              <el-radio :label="item.value" v-for="(item, index) in customerSexList" :key="index">{{ item.label
              }}</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="客户年龄" prop="customer_age">
          <el-input v-model="formCustomer.customer_age" placeholder="输入年龄" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="客户业务区域" prop="business_area_id">
          <el-select filterable multiple collapse-tags @change="businessAreaChange"
            v-model="formCustomer.business_area_id" placeholder="选择业务区域" clearable class="input-width">
            <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand_id">
          <el-select filterable v-model="formCustomer.brand_id" placeholder="选择品牌" clearable class="input-width">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道来源" prop="source">
          <el-select filterable v-model="formCustomer.source" placeholder="渠道来源" clearable class="input-width">
            <el-option label="品牌客户" :value="1"></el-option>
            <el-option label="电销" :value="2"></el-option>
            <el-option label="展会" :value="3"></el-option>
            <el-option label="转介绍" :value="4"></el-option>
            <el-option label="其他" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对客关注度" prop="customer_attention">
          <el-select filterable v-model="formCustomer.customer_attention" placeholder="选择对客关注度" clearable class="input-width">
            <el-option v-for="item in attentionList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户身份" prop="customer_identity">
          <el-select filterable v-model="formCustomer.customer_identity" placeholder="选择客户身份" clearable class="input-width">
            <el-option v-for="item in identityList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户态度" prop="customer_attitude">
          <el-select filterable v-model="formCustomer.customer_attitude" placeholder="选择客户态度" clearable class="input-width">
            <el-option v-for="item in attitudeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年度开店计划" prop="annual_store_opening_plan">
          <el-select filterable v-model="formCustomer.annual_store_opening_plan" placeholder="选择年度开店计划" clearable
            class="input-width">
            <el-option v-for="item in annualStoreOpeningPlan" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目前经营品牌" prop="current_operating_brand">
          <el-input v-model="formCustomer.current_operating_brand" placeholder="输入经营品牌" clearable
            class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="次社会关系" prop="secondary_social_relations">
          <el-select filterable v-model="formCustomer.secondary_social_relations" placeholder="选择次社会关系" clearable
            class="input-width">
            <el-option v-for="item in secondarySocialRelations" :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="投资能力" prop="investment_capability">
          <el-select filterable v-model="formCustomer.investment_capability" placeholder="选择投资能力" clearable class="input-width">
            <el-option v-for="item in investmentCapabilityList" :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员类型" prop="member_type">
          <el-select filterable v-model="formCustomer.member_type" placeholder="选择会员类型" clearable class="input-width">
            <el-option label="新会员" :value="1"></el-option>
            <el-option label="VIP会员" :value="2"></el-option>
            <el-option label="VVIP会员" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formCustomer.remark" placeholder="输入备注" clearable class="input-width"></el-input>
        </el-form-item>
        <div class="solid-box" v-if="formCustomer.partner_list.length"></div>
        <!-- 合伙人 -->
        <div v-for="(item, index) in formCustomer.partner_list" :key="index">
          <div class="user-title-box">
            联系人{{ index + 1 }}<span @click="delContacts(index)">删除</span>
          </div>
          <el-form-item label="联系人名称" :prop="'partner_list.' + index + '.customer_name'"
            :rules="customer_contactsRules">
            <el-input v-model="item.customer_name" placeholder="输入联系人名称" clearable class="input-width"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" :prop="'partner_list.' + index + '.customer_phone'" :rules="customer_phoneRules">
            <el-input maxlength="11" type="number" oninput="if(value.length > 11) value=value.slice(0, 11)"
              v-model="item.customer_phone" placeholder="输入联系方式" clearable class="input-width"></el-input>
          </el-form-item>
          <el-form-item label="客户身份" prop="customer_identity">
            <el-select filterable v-model="item.customer_identity" placeholder="选择客户身份" clearable class="input-width">
              <el-option v-for="item in identityList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="对客关注度" prop="customer_attention">
            <el-select filterable v-model="item.customer_attention" placeholder="选择对客关注度" clearable class="input-width">
              <el-option v-for="item in attentionList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户态度" prop="customer_attitude">
            <el-select filterable v-model="item.customer_attitude" placeholder="选择客户态度" clearable class="input-width">
              <el-option v-for="item in attitudeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年度开店计划" prop="annual_store_opening_plan">
            <el-select filterable v-model="item.annual_store_opening_plan" placeholder="选择年度开店计划" clearable class="input-width">
              <el-option v-for="item in annualStoreOpeningPlan" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目前经营品牌" prop="current_operating_brand">
            <el-input v-model="item.current_operating_brand" placeholder="输入经营品牌" clearable
              class="input-width"></el-input>
          </el-form-item>
          <el-form-item label="次社会关系" prop="secondary_social_relations">
            <el-select filterable v-model="item.secondary_social_relations" placeholder="选择次社会关系" clearable class="input-width">
              <el-option v-for="item in secondarySocialRelations" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="投资能力" prop="investment_capability">
            <el-select filterable v-model="item.investment_capability" placeholder="选择投资能力" clearable class="input-width">
              <el-option v-for="item in investmentCapabilityList" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="item.remark" placeholder="输入备注" clearable class="input-width"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addContacts">新增联系人</el-button>
        <el-button type="primary" @click="saveSubmit('dLogUserRules')" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import adminApi from "@/api/adminApi";
import commonApi from "@/api/common";
import brandApi from "@/api/brandApi";
var phoneRule = (rule, value, callback) => {
  if (!/^1\d{10}$/.test(value)) {
    return callback(new Error("请输入正确手机号"));
  } else {
    callback();
  }
};
var password = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("密码不能为空"));
  } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/.test(value)) {
    callback(new Error("密码须8-16位,包含大小写字母、数字"));
  } else {
    callback();
  }
};
export default {
  name: 'addCustomerPage',
  data() {
    return {
      formCustomer: {
        admin_id: "",
        imgUrl: "",
        imgFile: null,
        name: "",
        phone: "",
        password: "",
        brand_id: "",
        business_area: [],
        business_area_id: [],
        customer_type: "",
        customer_sex: 1,
        customer_age: "",
        customer_identity: "",
        customer_attention: "",
        customer_attitude: "",
        current_operating_brand: "",
        secondary_social_relations: "",
        investment_capability: "",
        annual_store_opening_plan: "",
        member_type: '',
        remark: "",
        source: "",
        partner_list: [
          // {
          //   customer_name: '',
          //   customer_phone: '',
          //   customer_identity: '',
          //   customer_attention: '',
          //   customer_attitude: '',
          //   current_operating_brand: '',
          //   secondary_social_relations: '',
          //   investment_capability: '',
          //   annual_store_opening_plan: '',
          //   remark: '',
          // }
        ], //合伙人列表
      },
      attentionList: [
        {
          label: "持续重点关注",
          value: 1,
        },
        {
          label: "持续关注",
          value: 2,
        },
        {
          label: "定期关注",
          value: 3,
        },
        {
          label: "不定期关注",
          value: 4,
        },
        {
          label: "一般关注",
          value: 5,
        },
      ],
      attitudeList: [
        {
          label: "积极主动",
          value: 1,
        },
        {
          label: "沟通顺畅",
          value: 2,
        },
        {
          label: "敷衍了事",
          value: 3,
        },
        {
          label: "拒不配合",
          value: 4,
        },
      ],
      identityList: [
        {
          label: "老板",
          value: 1,
        },
        {
          label: "合伙人",
          value: 2,
        },
        {
          label: "项目负责人",
          value: 3,
        },
        {
          label: "签约人",
          value: 4,
        },
      ],
      customerTypeList: [
        {
          label: "VIP客户",
          value: 1,
        },
        {
          label: "优质客户",
          value: 2,
        },
        {
          label: "普通老客户",
          value: 3,
        },
        {
          label: "优质新客户",
          value: 4,
        },
        {
          label: "普通新客户",
          value: 5,
        },
      ],
      investmentCapabilityList: [
        {
          label: "100w以下",
          value: 1,
        },
        {
          label: "100-500w",
          value: 2,
        },
        {
          label: "500-1000w",
          value: 3,
        },
        {
          label: "1000w以上",
          value: 4,
        },
      ],
      annualStoreOpeningPlan: [
        {
          label: "不连续且少量开店",
          value: 1,
        },
        {
          label: "不连续且大量开店",
          value: 2,
        },
        {
          label: "持续且少量开店",
          value: 3,
        },
        {
          label: "持续且大量开店",
          value: 4,
        },
      ],
      customerSexList: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
      ],
      secondarySocialRelations: [
        {
          label: "品牌方关系户",
          value: 1,
        },
        {
          label: "我司关系户",
          value: 2,
        },
        {
          label: "政府关系户",
          value: 3,
        },
        {
          label: "一般关系",
          value: 4,
        },
      ],
      dLogUserRules: {
        member_type: [
          {
            required: true,
            message: "请选择会员类型",
            trigger: "change",
          },
        ],
        customer_type: [
          {
            required: true,
            message: "请选择客户类型",
            trigger: "change",
          },
        ],
        imgUrl: [
          {
            required: true,
            message: "请上传头像",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入用户名称",
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            validator: phoneRule,
            trigger: "change",
          },
        ],
        password: [
          {
            validator: password,
            required: true,
            trigger: "change",
          },
        ],
        business_area_id: [
          {
            required: true,
            message: "请选择业务区域",
            trigger: "change",
          },
        ],
        customer_sex: [
          {
            required: true,
            message: "请选择客户性别",
            trigger: "change",
          },
        ],
        brand_id: [
          {
            required: true,
            message: "请选择客户品牌",
            trigger: "change",
          },
        ],
      },
      customer_contactsRules: [
        {
          required: true,
          message: "请输入用户名称",
          trigger: "change",
        },
      ],
      customer_phoneRules: [
        {
          required: true,
          validator: phoneRule,
          trigger: "change",
        },
      ],
      cityList: [],
      brandList: [],
      submitBtn: false,
    };
  },
  computed: {
    hisList() {
      return this.$store.getters.routerHis;
    },
    path() {
      return this.$route.path;
    },
  },
  mounted() {
    this.getAreaList();
    this.getBrandList();
    if (this.$route.query.id) {
      this.getUserDetail(this.$route.query.id);
    }
  },
  methods: {
    // 添加客户联系人
    addContacts() {
      let formCustomer = this.formCustomer;
      formCustomer.partner_list.push({
        customer_name: "",
        customer_phone: "",
        customer_identity: "",
        customer_attention: "",
        customer_attitude: "",
        current_operating_brand: "",
        secondary_social_relations: "",
        investment_capability: "",
        annual_store_opening_plan: "",
        remark: "",
      });
      this.formCustomer = formCustomer;
    },
    // 删除客户联系人
    delContacts(index) {
      let formCustomer = this.formCustomer;
      formCustomer.partner_list.splice(index, 1);
      this.formCustomer = formCustomer;
    },
    // 业务区域选择
    businessAreaChange(e) {
      let formCustomer = this.formCustomer;
      formCustomer.business_area = [];
      let cityList = this.cityList;
      e.forEach((k) => {
        let index = cityList.findIndex((item) => {
          return item.id == k;
        });
        formCustomer.business_area.push(cityList[index].name);
      });
      this.formCustomer = formCustomer;
    },
    // 操作用户弹窗 - 头像数据
    change_file(e) {
      this.formCustomer.imgUrl = e.url;
      this.formCustomer.imgFile = e.raw;
    },
    // 操作用户弹窗 - 提交
    saveSubmit(formName) {
      //平台用户关联
      let formCustomer = this.formCustomer;
      //   console.log(formCustomer);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 客户添加修改
          let partner_list = JSON.parse(
            JSON.stringify(formCustomer.partner_list)
          );
          partner_list.forEach((item) => {
            item.annual_store_opening_plan =
              item.annual_store_opening_plan || 0;
            item.current_operating_brand = item.current_operating_brand || "";
            item.customer_attention = item.customer_attention || 0;
            item.customer_attitude = item.customer_attitude || 0;
            item.customer_identity = item.customer_identity || 0;
            item.investment_capability = item.investment_capability || 0;
            item.secondary_social_relations =
              item.secondary_social_relations || 0;
          });
          let formdata = new FormData();
          let data = {
            member_type: formCustomer.member_type,

            identity: 4,
            name: formCustomer.name,
            phone: formCustomer.phone,
            password: "",
            province_id: 0,
            city_id: 0,
            county_id: 0,
            role_id: 0,
            position_id: 0,
            brand_id: formCustomer.brand_id || 0,
            business_area: formCustomer.business_area,
            business_area_id: formCustomer.business_area_id,
            customer_type: formCustomer.customer_type || 0,
            customer_sex: formCustomer.customer_sex || 0,
            customer_age: formCustomer.customer_age,

            customer_identity: formCustomer.customer_identity || 0,
            customer_attention: formCustomer.customer_attention || 0,
            customer_attitude: formCustomer.customer_attitude || 0,
            current_operating_brand: formCustomer.current_operating_brand || "",
            secondary_social_relations:
              formCustomer.secondary_social_relations || 0,
            investment_capability: formCustomer.investment_capability || 0,
            annual_store_opening_plan:
              formCustomer.annual_store_opening_plan || 0,
            remark: formCustomer.remark,
            partner_list: partner_list,
            admin_id: formCustomer.admin_id || "",
            source: formCustomer.source,
          };
          //   console.log(data, "添加修改用户参数");
          if (formCustomer.imgFile) {
            formdata.append("image", formCustomer.imgFile || "");
          }
          formdata.append("data", JSON.stringify(data));
          if (!formCustomer.admin_id) {
            this.addUserApi(formdata);
          } else {
            this.updUser(formdata);
          }
        } else {
          return false;
        }
      });
    },
    // 省市区
    getAreaList() {
      commonApi.getAreaList().then((res) => {
        console.log(res, "省市区");
        if (res.code == 200) {
          this.cityList = res.data;
        }
      });
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 999,
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        });
    },
    // 添加客户
    addUserApi(userForm) {
      this.submitBtn = true;
      adminApi
        .addUser(userForm)
        .then((res) => {
          console.log(res, "addUser");
          if (res.code == 200) {
            this.$goBackTab(this);
            this.$message({
              type: "success",
              message: "添加成功!",
            });
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
          this.$message.error(err.message);
        });
    },
    // 更新客户
    updUser(userForm) {
      this.submitBtn = true;
      adminApi
        .updUser(userForm)
        .then((res) => {
          console.log(res, "updUser");
          if (res.code == 200) {
            this.$goBackTab(this);
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          } else {
            this.$message.error(res.message);
          }
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
          this.$message.error(err.message);
        });
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },
    // 客户详情
    getUserDetail(user_id) {
      adminApi.getUserDetail({ user_id }).then((res) => {
        console.log(res, "客户详情");
        if (res.code == 200) {
          let business_area_id = [];
          let business_area = [];
          if (res.data.business_area_id) {
            res.data.business_area_id.split(",").forEach((item) => {
              business_area_id.push(Number(item));
            });
          }
          if (res.data.business_area) {
            res.data.business_area.split(",").forEach((item) => {
              business_area.push(item);
            });
          }
          res.data.partner_list.forEach((item) => {
            item.customer_identity = item.customer_identity || "";
            item.admin_id = item.admin_id || "";
            item.annual_store_opening_plan =
              item.annual_store_opening_plan || "";
            item.customer_age = item.customer_age || "";
            item.customer_attention = item.customer_attention || "";
            item.customer_attitude = item.customer_attitude || "";
            item.customer_sex = item.customer_sex || "";
            item.investment_capability = item.investment_capability || "";
            item.secondary_social_relations =
              item.secondary_social_relations || "";
          });
          this.formCustomer = {
            admin_id: res.data.id || "",
            imgUrl: res.data.image || "",
            imgFile: null,
            name: res.data.name || "",
            phone: res.data.phone || "",
            password: "",
            city: [],
            brand_id: res.data.brand_id || "",
            business_area: business_area || "",
            business_area_id: business_area_id || "",
            customer_type: res.data.customer_type || "",
            customer_sex: res.data.customer_sex || "",
            customer_age: res.data.customer_age || "",
            customer_identity: res.data.customer_identity || "",
            customer_attention: res.data.customer_attention || "",
            customer_attitude: res.data.customer_attitude || "",
            current_operating_brand: res.data.current_operating_brand || "",
            secondary_social_relations:
              res.data.secondary_social_relations || "",
            investment_capability: res.data.investment_capability || "",
            annual_store_opening_plan: res.data.annual_store_opening_plan || "",
            remark: res.data.remark || "",
            partner_list: res.data.partner_list || [],
            member_type: res.data.member_type || '',
            source: res.data.source || '',
          };
          this.$nextTick(() => {
            this.$refs.dLogUserRules.clearValidate();
          })
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/addPage.scss";
</style>